package com.caregiver.watch.business.data.task;

import com.caregiver.watch.business.data.service.AlgorithmService;
import com.caregiver.watch.business.user.model.po.UserDevice;
import com.caregiver.watch.business.user.service.UserDeviceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;

import static com.caregiver.watch.common.constant.NumberConstants.FIVE_THOUSAND;
import static com.caregiver.watch.common.constant.NumberConstants.ONE;
import static com.caregiver.watch.common.constant.NumberConstants.ZERO;

/**
 * 睡眠数据计算任务类
 */
@AllArgsConstructor
@Component
@Slf4j
public class SleepDataCalculationTask {

    private final UserDeviceService userDeviceService;
    private final AlgorithmService algorithmService;
    private final ExecutorService sleepDataCalculationWorkThreadPool;

    /**
     * 睡眠数据计算 定时任务
     *  8:00-23:00 每小时执行一次
     */
    @Scheduled(cron = "0 0 8-23/1 * * *")
    @Async("sleepDataCalculationSelectThreadPool")
    public void sleepDataCalculation() {
        // 睡眠数据计算逻辑
        log.info("睡眠数据计算任务开始执行...");
        // 最大执行次数
        int maxExecuteCount = 500;
        // 拉取全部设备ID 一次拉5000个
        String lastDeviceUuId = null;
        do {
            List<UserDevice> userDevices = userDeviceService.queryDeviceUuIds(lastDeviceUuId, FIVE_THOUSAND);
            if (CollectionUtils.isEmpty(userDevices)) {
                break;
            }
            sleepDataCalculationWorkThreadPool.submit(() -> algorithmService.sleepDataCalculation(userDevices));
            lastDeviceUuId = userDevices.get(userDevices.size() - ONE).getDeviceUuid();
        } while (--maxExecuteCount > ZERO);
        log.info("睡眠数据计算任务结束...");
    }
}
